import pymssql
import pymysql
import yaml
from urllib import parse
from sqlalchemy import create_engine
import os

current_file_path = os.path.abspath(__file__)
current_directory = os.path.dirname(current_file_path)
yaml_file_path = os.path.join(current_directory, 'db.yaml')
def conn_db(conn_name,db_type="mysql"):
    with open(yaml_file_path) as f:
        dbs = yaml.load(f, Loader=yaml.Loader)
    db_para = dbs[conn_name]
    if db_type == "mysql":
        conn = pymysql.connect(host=db_para['host'],port=db_para['port'],user=db_para['user'],password=db_para['password'],database=db_para['database'])
    if db_type == "sqlserver":
        conn = pymssql.connect(host=db_para['host'],port=db_para['port'],user=db_para['user'],password=db_para['password'], database=db_para['database'],tds_version="7.0")
    return conn

def conn_db_engine(conn_name):
    with open(yaml_file_path) as f:
        dbs = yaml.load(f, Loader=yaml.Loader)
    db_para = dbs[conn_name]
    engine = create_engine('mysql+pymysql://{}:{}@{}:{}/{}'.format(db_para['user'],parse.quote_plus(db_para['password']),db_para['host'],db_para['port'],db_para['database']))
    return engine





